﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SocialNetwork.Twitter;
using System.Drawing;
using System.Globalization;
using System.Drawing.Design;

[assembly: WebResource(TweetButton.TWITTER_ICON, "image/png")]

namespace SocialNetwork
{
    namespace Twitter
    {
        #region Enum
        public enum Implementations
        {
            IFrame,
            JavaScript
        }

        public enum LayoutOption
        {
            Horizontal,
            Vertical,
            None
        }
        #endregion

        [ToolboxData("<{0}:TweetButton runat=server></{0}:TweetButton>")]
        [ToolboxBitmap(typeof(TweetButton), TweetButton.TWITTER_ICON)]
        public class TweetButton : SocialNetworkControl
        {
            public const string TWITTER_ICON = "SocialNetwork.Images.twitter.jpg";

            private List<Related> _items;

            #region Properties
            /// <summary>
            /// 
            /// </summary>
            [Description("")]
            [DefaultValue(Implementations.IFrame)]
            [Category("SocialNetwork")]
            public Implementations Mode { get; set; }

            /// <summary>
            /// URL of the page to share
            /// </summary>
            [DefaultValue("")]
            [Description("URL of the page to share")]
            [Category("SocialNetwork")]
            public string Url { get; set; }

            [DefaultValue(true)]
            [Category("SocialNetwork")]
            public bool UseCurrentPage
            {
                get
                {
                    return GetData<bool>("UseCurrentPage", true);
                }
                set
                {
                    ViewState["UseCurrentPage"] = value;
                }
            }

            /// <summary>
            /// Screen name of the user to attribute the Tweet to
            /// </summary>
            [DefaultValue("")]
            [Description("Screen name of the user to attribute the Tweet to")]
            [Category("SocialNetwork")]
            public string Via { get; set; }

            /// <summary>
            /// Default Tweet text
            /// </summary>
            [DefaultValue("")]
            [Description("Default Tweet text")]
            [Category("SocialNetwork")]
            public string Text { get; set; }

            /// <summary>
            /// Related accounts
            /// </summary>
            [DefaultValue("")]
            [Description("Related accounts")]
            [PersistenceMode(PersistenceMode.InnerProperty)]
            [Category("SocialNetwork")]
            public List<Related> Related
            {
                get
                {
                    if (_items == null)
                        _items = new List<Related>();

                    return _items;
                }
            }

            /// <summary>
            /// Count box position
            /// </summary>
            [DefaultValue(LayoutOption.Horizontal)]
            [Description("Count box position")]
            [Category("SocialNetwork")]
            public LayoutOption Layout { get; set; }

            /// <summary>
            /// The language for the Tweet Button
            /// </summary>
            [DefaultValue("")]
            [Description("The language for the Tweet Button")]
            [Category("SocialNetwork")]
            public CultureInfo Culture { get; set; }

            /// <summary>
            /// The URL to which your shared URL resolves to
            /// </summary>
            [DefaultValue("")]
            [Description("The URL to which your shared URL resolves to")]
            [Category("SocialNetwork")]
            public string CountUrl { get; set; }


            #endregion

            #region Validator
            private void Validate()
            {
                ValidateRelated();
                ValidateUrl();
            }

            private void ValidateUrl()
            {
                if (string.IsNullOrEmpty(Url) && !UseCurrentPage)
                {
                    throw new Exception("'url' parameter does not contain a valid URL.");
                }
            }

            private void ValidateRelated()
            {
                if (Related.Count > 0)
                {
                    if (Related.Any(x => x.Account.Contains(",") ||
                                    x.Account.Contains(":") ||
                                    (x.Summary != null && (x.Summary.Contains(",") ||
                                    x.Summary.Contains(":")))))
                    {
                        throw new Exception("Related should not include commas or colons");
                    }
                }
            }
            #endregion

            #region Render

            protected override void RenderContents(HtmlTextWriter output)
            {
                if (!DesignMode)
                {
                    Validate();

                    if (Mode == Implementations.IFrame)
                    {
                        RenderIFrame(output);
                    }
                    else if (Mode == Implementations.JavaScript)
                    {
                        RenderJS(output);
                    }
                }
                else
                {
                    RenderDesignMode(output);
                }
            }

            #region JS
            private void RenderJS(HtmlTextWriter output)
            {
                RenderJSSrc(output);
                RenderA(output);
            }

            private void RenderA(HtmlTextWriter output)
            {
                output.AddAttribute("href", "http://twitter.com/share");
                output.AddAttribute("class", "twitter-share-button");
                output.AddAttribute("data-url", GetHref());
                if (!string.IsNullOrEmpty(Via))
                {
                    output.AddAttribute("data-via", Via);
                }

                if (!string.IsNullOrEmpty(Text))
                {
                    output.AddAttribute("data-text", Text);
                }

                output.AddAttribute("data-count", Layout.ToString().ToLower());

                if (Culture != null)
                {
                    output.AddAttribute("data-lang", Culture.TwoLetterISOLanguageName);
                }

                if (!string.IsNullOrEmpty(CountUrl))
                {
                    output.AddAttribute("data-ounturl", CountUrl);
                }

                if (Related.Count > 0)
                {
                    string rel = "";
                    foreach (var item in Related)
                    {
                        rel += item.ToString() + ",";
                    }

                    rel = rel.Remove(rel.Length - 1);
                    output.AddAttribute("data-related", rel);
                }

                output.RenderBeginTag(HtmlTextWriterTag.A);
                output.Write("Tweet");
                output.RenderEndTag();
            }

            private void RenderJSSrc(HtmlTextWriter output)
            {
                output.AddAttribute("src", "http://platform.twitter.com/widgets.js");
                output.RenderBeginTag(HtmlTextWriterTag.Script);
                output.RenderEndTag();
            }
            #endregion

            #region IFrame
            private void RenderIFrame(HtmlTextWriter output)
            {
                RenderIFrameAttributes(output);
                RenderIFrameStyle(output);

                output.RenderBeginTag("iframe");
                output.RenderEndTag();
            }

            private void RenderIFrameStyle(HtmlTextWriter output)
            {
                output.AddStyleAttribute("border", "none");
                output.AddStyleAttribute("overflow", "hidden");
                output.AddStyleAttribute("width", "130");
                output.AddStyleAttribute("height", "50");
            }

            private void RenderIFrameAttributes(HtmlTextWriter output)
            {
                string src = GetLink();

                output.AddAttribute("src", src);
                output.AddAttribute("scrolling", "no");
                output.AddAttribute("frameborder", "0");
                output.AddAttribute("allowTransparency", "true");
            }

            private string GetLink()
            {
                string link = "http://platform.twitter.com/widgets/tweet_button.html?";

                link += UrlParameter("url", HttpUtility.UrlEncode(GetHref()));

                if (!string.IsNullOrEmpty(Via))
                {
                    link += UrlParameter("via", Via);
                }

                if (!string.IsNullOrEmpty(Text))
                {
                    link += UrlParameter("text", Text);
                }

                link += UrlParameter("count", HttpUtility.UrlEncode(Layout.ToString().ToLower()));

                if (Culture != null)
                {
                    link += UrlParameter("lang", Culture.TwoLetterISOLanguageName);
                }

                if (!string.IsNullOrEmpty(CountUrl))
                {
                    link += UrlParameter("counturl", HttpUtility.UrlEncode(CountUrl));
                }

                if (Related.Count > 0)
                {
                    string rel = "";
                    foreach (var item in Related)
                    {
                        rel += item.ToString() + ",";
                    }

                    rel = rel.Remove(rel.Length - 1);
                    link += UrlParameter("related", rel);
                }

                return link;
            }

            #endregion

            private void RenderDesignMode(HtmlTextWriter output)
            {
                //output.AddAttribute(HtmlTextWriterAttribute.Width, GetWidth());
                //output.AddAttribute(HtmlTextWriterAttribute.Height, GetHeight());
                output.AddStyleAttribute(HtmlTextWriterStyle.BackgroundColor, "silver");
                output.AddStyleAttribute(HtmlTextWriterStyle.BorderStyle, "solid");
                output.AddStyleAttribute(HtmlTextWriterStyle.BorderWidth, "1px");
                output.RenderBeginTag(HtmlTextWriterTag.Table);
                output.RenderBeginTag(HtmlTextWriterTag.Tr);

                output.RenderBeginTag(HtmlTextWriterTag.Td);
                output.AddAttribute(HtmlTextWriterAttribute.Src, Page.ClientScript.GetWebResourceUrl(typeof(TweetButton), TweetButton.TWITTER_ICON));
                output.RenderBeginTag(HtmlTextWriterTag.Img);
                output.RenderEndTag(); // img
                output.RenderEndTag(); // td
                output.RenderEndTag(); //tr
                output.RenderEndTag(); // table
            }
            #endregion

            private string GetHref()
            {
                if (UseCurrentPage && !DesignMode)
                {
                    return HttpContext.Current.Request.Url.ToString();
                }

                return Url;
            }

            private static string UrlParameter(string key, string value)
            {
                return string.Format("{0}={1}&", key, value);
            }

           
        }
    }
}
